package com.tdtxdcxm.ruralcommunity.slice;

import com.tdtxdcxm.ruralcommunity.ResourceTable;
import com.tdtxdcxm.ruralcommunity.appruntime.DataCenterControl;
import com.tdtxdcxm.ruralcommunity.httpmanagers.ThreadPoolUtil;
import com.tdtxdcxm.ruralcommunity.items.LCArryListContentItem;
import com.tdtxdcxm.ruralcommunity.myutils.MyTools;
import com.tdtxdcxm.ruralcommunity.providers.LCProviderForContent;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;
import ohos.utils.zson.ZSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class UserContentListSlice extends AbilitySlice {
    private Button usercontent_backbut;
    private ListContainer usercontent_lc;

    /*<****************http请求用户内容列表与收藏列表数据区域*****************/
    public void DownDataUserContentListInfo(String type){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;
            String urlString = DataCenterControl.serverIpWithPort + "usercontentlist/?";
            try {
                URL url = new URL(urlString);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("username=");
                    stringBuilder.append(DataCenterControl.userName);
                    stringBuilder.append("&type=");
                    switch(type){
                        case "dtlist":
                            stringBuilder.append("dtlist");
                            break;
                        case "xmlist":
                            stringBuilder.append("xmlist");
                            break;
                        case "wzlist":
                            stringBuilder.append("wzlist");
                            break;
                        case "collectlist":
                            stringBuilder.append("collectlist");
                            break;
                        default:
                            break;
                    }
                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);

                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();


                    InputStream inputStream = null;
                    try {
                        inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = outputStream.toString();
                    //System.out.println("---httpURLConnection>>>>" + result);
                    if(result.indexOf("sum") != -1){
                        //请求全站动态成功
                        String finalResult = result;
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                switch (type) {
                                    case "dtlist":
                                        ZSONObject zsonobject_dt = ZSONObject.stringToZSON(finalResult);
                                        int sum_dt = Integer.parseInt(zsonobject_dt.getString("sum"));
                                        DataCenterControl.userdt_listcontainer_list.clear();
                                        for(int i = 0;i < sum_dt;i++){
                                            ZSONObject t = ZSONObject.stringToZSON(zsonobject_dt.getString(String.valueOf(i)));

                                            int detail_len = t.getString("DETAIL").length();
                                            DataCenterControl.userdt_listcontainer_list.add(
                                                    new LCArryListContentItem(t.getString("CONTENT_ID")
                                                            ,t.getString("TYPE")
                                                            ,t.getString("DATE")
                                                            ,t.getString("READVALUE")
                                                            ,t.getString("DETAIL").substring(12,detail_len - 1 - 1).replace("\\n","\n")
                                                            ,t.getString("USER_ID")
                                                            ,DataCenterControl.fields[Integer.parseInt(t.getString("FIELD_ID")) - 1]
                                                    )
                                            );
                                        }
                                        if(DataCenterControl.userDtListContainerProvider != null){
                                            DataCenterControl.userDtListContainerProvider.notifyDataChanged();
                                        }
                                        MyTools.toastShow("用户动态下载成功！", UserContentListSlice.this.getContext());
                                        break;
                                    case "xmlist":
                                        ZSONObject zsonobject_xm = ZSONObject.stringToZSON(finalResult);
                                        int sum_xm = Integer.parseInt(zsonobject_xm.getString("sum"));
                                        DataCenterControl.userxm_listcontainer_list.clear();
                                        for(int i = 0;i < sum_xm;i++){
                                            ZSONObject t = ZSONObject.stringToZSON(zsonobject_xm.getString(String.valueOf(i)));

                                            int detail_len = t.getString("DETAIL").length();
                                            DataCenterControl.userxm_listcontainer_list.add(
                                                    new LCArryListContentItem(t.getString("CONTENT_ID")
                                                            ,t.getString("TYPE")
                                                            ,t.getString("DATE")
                                                            ,t.getString("READVALUE")
                                                            ,t.getString("DETAIL")
                                                            ,t.getString("USER_ID")
                                                            ,DataCenterControl.fields[Integer.parseInt(t.getString("FIELD_ID")) - 1]
                                                    )
                                            );
                                        }
                                        if(DataCenterControl.userXmListContainerProvider != null){
                                            DataCenterControl.userXmListContainerProvider.notifyDataChanged();
                                        }
                                        MyTools.toastShow("用户项目下载成功！", UserContentListSlice.this.getContext());
                                        break;
                                    case "wzlist":
                                        ZSONObject zsonobject_wz = ZSONObject.stringToZSON(finalResult);
                                        int sum_wz = Integer.parseInt(zsonobject_wz.getString("sum"));
                                        DataCenterControl.userwz_listcontainer_list.clear();
                                        for(int i = 0;i < sum_wz;i++){
                                            ZSONObject t = ZSONObject.stringToZSON(zsonobject_wz.getString(String.valueOf(i)));

                                            int detail_len = t.getString("DETAIL").length();
                                            DataCenterControl.userwz_listcontainer_list.add(
                                                    new LCArryListContentItem(t.getString("CONTENT_ID")
                                                            ,t.getString("TYPE")
                                                            ,t.getString("DATE")
                                                            ,t.getString("READVALUE")
                                                            ,t.getString("DETAIL").substring(12,detail_len - 1 - 1).replace("\\n","\n")
                                                            ,t.getString("USER_ID")
                                                            ,DataCenterControl.fields[Integer.parseInt(t.getString("FIELD_ID")) - 1]
                                                    )
                                            );
                                        }
                                        if(DataCenterControl.userWzListContainerProvider != null){
                                            DataCenterControl.userWzListContainerProvider.notifyDataChanged();
                                        }
                                        MyTools.toastShow("用户文章下载成功！", UserContentListSlice.this.getContext());
                                        break;
                                    case "collectlist":
                                        ZSONObject zsonobject_collect = ZSONObject.stringToZSON(finalResult);
                                        int sum_collect = Integer.parseInt(zsonobject_collect.getString("sum"));
                                        DataCenterControl.usercollect_listcontainer_list.clear();
                                        for(int i = 0;i < sum_collect;i++){
                                            ZSONObject t = ZSONObject.stringToZSON(zsonobject_collect.getString(String.valueOf(i)));
                                            String field = t.getString("TYPE");
                                            int detail_len = t.getString("DETAIL").length();
                                            if(field.equals("动态") || field.equals("文章")){
                                                DataCenterControl.usercollect_listcontainer_list.add(
                                                        new LCArryListContentItem(t.getString("CONTENT_ID")
                                                                ,t.getString("TYPE")
                                                                ,t.getString("DATE")
                                                                ,t.getString("READVALUE")
                                                                ,t.getString("DETAIL").substring(12,detail_len - 1 - 1).replace("\\n","\n")
                                                                ,t.getString("USER_ID")
                                                                ,DataCenterControl.fields[Integer.parseInt(t.getString("FIELD_ID")) - 1]
                                                        )
                                                );
                                            }
                                            if(field.equals("项目")){
                                                DataCenterControl.usercollect_listcontainer_list.add(
                                                        new LCArryListContentItem(t.getString("CONTENT_ID")
                                                                ,t.getString("TYPE")
                                                                ,t.getString("DATE")
                                                                ,t.getString("READVALUE")
                                                                ,t.getString("DETAIL")
                                                                ,t.getString("USER_ID")
                                                                ,DataCenterControl.fields[Integer.parseInt(t.getString("FIELD_ID")) - 1]
                                                        )
                                                );
                                            }
                                        }
                                        if(DataCenterControl.userCollectListContainerProvider != null){
                                            DataCenterControl.userCollectListContainerProvider.notifyDataChanged();
                                        }
                                        MyTools.toastShow("用户收藏下载成功！", UserContentListSlice.this.getContext());
                                        break;
                                    default:
                                        MyTools.toastShow("用户未知下载成功！", UserContentListSlice.this.getContext());
                                        break;
                                }
                            }
                        });
                    }
                    else if(result.equals("NULL")){
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                switch(type){
                                    case "dtlist":
                                        DataCenterControl.userdt_listcontainer_list.clear();
                                        if(DataCenterControl.userDtListContainerProvider != null){
                                            DataCenterControl.userDtListContainerProvider.notifyDataChanged();
                                        }
                                        break;
                                    case "xmlist":
                                        DataCenterControl.userxm_listcontainer_list.clear();
                                        if(DataCenterControl.userXmListContainerProvider != null){
                                            DataCenterControl.userXmListContainerProvider.notifyDataChanged();
                                        }
                                        break;
                                    case "wzlist":
                                        DataCenterControl.userwz_listcontainer_list.clear();
                                        if(DataCenterControl.userWzListContainerProvider != null){
                                            DataCenterControl.userWzListContainerProvider.notifyDataChanged();
                                        }
                                        break;
                                    case "collectlist":
                                        DataCenterControl.usercollect_listcontainer_list.clear();
                                        if(DataCenterControl.userCollectListContainerProvider != null){
                                            DataCenterControl.userCollectListContainerProvider.notifyDataChanged();
                                        }
                                        break;
                                }
                                MyTools.toastShow("用户内容为空！", UserContentListSlice.this.getContext());
                            }
                        });
                    }
                    else{
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                switch (type) {
                                    case "dtlist":
                                        MyTools.toastShow("用户动态下载失败！", UserContentListSlice.this.getContext());
                                        break;
                                    case "xmlist":
                                        MyTools.toastShow("用户项目下载失败！", UserContentListSlice.this.getContext());
                                        break;
                                    case "wzlist":
                                        MyTools.toastShow("用户文章下载失败！", UserContentListSlice.this.getContext());
                                        break;
                                    case "collectlist":
                                        MyTools.toastShow("用户收藏下载失败！", UserContentListSlice.this.getContext());
                                        break;
                                    default:
                                        MyTools.toastShow("用户未知下载失败！", UserContentListSlice.this.getContext());
                                        break;
                                }
                            }
                        });
                    }
                }
            } catch (IOException e) {
            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });
    }
    /******************http请求用户内容列表与收藏列表数据区域***************>*/

    /*<****************http删除用户内容数据区域*****************/
    public void UpDataDeleteUserContentInfo(String type,String contentid,ArrayList<LCArryListContentItem> list,LCProviderForContent lcProviderForContent,int list_i){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;
            String urlString = DataCenterControl.serverIpWithPort + "deleteusercontent/?";

            try {
                URL url = new URL(urlString);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("username=");
                    stringBuilder.append(DataCenterControl.userName);
                    stringBuilder.append("&contentid=");
                    stringBuilder.append(contentid);

                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);

                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();


                    InputStream inputStream = null;
                    try {
                        inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = outputStream.toString();

                    if(result.equals("OK")){
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                list.remove(list_i);
                                lcProviderForContent.notifyDataChanged();
                                MyTools.toastShow("删除成功！",UserContentListSlice.this.getContext());
                            }
                        });
                    }
                    else if(result.equals("NO")){
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                MyTools.toastShow("删除失败！刷可刷新加载！", UserContentListSlice.this.getContext());
                            }
                        });
                    }
                }
            } catch (IOException e) {
            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });
    }
    /******************http删除用户内容数据区域***************>*/

    /*<----------------------------------------初始化ListContainer区域----------------------------------*/
    public  void initListContainer(ListContainer listContainer,String listContainerName,AbilitySlice slice,String type){
        if(listContainer == null){
            return;
        }
        listContainer.setName(listContainerName);
        LCProviderForContent lcProviderForContent = null;

        switch (type) {
            case "dtlist":
                lcProviderForContent = new LCProviderForContent(DataCenterControl.userdt_listcontainer_list,slice);
                DataCenterControl.userDtListContainerProvider = lcProviderForContent;
                break;
            case "xmlist":
                lcProviderForContent = new LCProviderForContent(DataCenterControl.userxm_listcontainer_list,slice);
                DataCenterControl.userXmListContainerProvider = lcProviderForContent;
                break;
            case "wzlist":
                lcProviderForContent = new LCProviderForContent(DataCenterControl.userwz_listcontainer_list,slice);
                DataCenterControl.userWzListContainerProvider = lcProviderForContent;
                break;
            case "collectlist":
                lcProviderForContent = new LCProviderForContent(DataCenterControl.usercollect_listcontainer_list,slice);
                DataCenterControl.userCollectListContainerProvider = lcProviderForContent;
                break;
            default:
                break;
        }

        if(lcProviderForContent != null){
            listContainer.setItemProvider(lcProviderForContent);
        }

        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Text typeText = (Text) ((DirectionalLayout)component).getComponentAt(0);
                switch(typeText.getText()){
                    case "项目":
                        slice.present(new XmDetails(),new Intent().setParam("listContainerName",listContainer.getName()).setParam("i", i));
                        break;
                    case "动态":
                    case "文章":
                        slice.present(new DtAndWzDetails(),new Intent().setParam("listContainerName",listContainer.getName()).setParam("i", i));
                        break;
                    default:
                        break;
                }
            }
        });

        listContainer.setItemLongClickedListener(new ListContainer.ItemLongClickedListener() {
            @Override
            public boolean onItemLongClicked(ListContainer listContainer, Component component, int i, long l) {
                LCProviderForContent lcpfc = (LCProviderForContent) listContainer.getItemProvider();
                LCArryListContentItem lcarryListContentItem = (LCArryListContentItem) lcpfc.getItem(i);
                if(!listContainer.getName().equals("usercollectlc")){
                    UpDataDeleteUserContentInfo("delete",lcarryListContentItem.getContent_id(),lcpfc.list,lcpfc,i);
                }
                return true;
            }
        });
    }
    /*-----------------------------------------初始化ListContainer区域---------------------------------->*/


    private void initUCLSComponents(){
        usercontent_backbut = (Button) findComponentById(ResourceTable.Id_usercontent_backbut);
        usercontent_lc = (ListContainer) findComponentById(ResourceTable.Id_usercontent_lc);

        usercontent_backbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                terminate();
            }
        });
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_usercontent_item_listcontainer);
        initUCLSComponents();
        String type = intent.getStringParam("type");
        switch(type){
            case "dtlist":
                initListContainer(usercontent_lc,"userdtlc",this,type);
                break;
            case "xmlist":
                initListContainer(usercontent_lc,"userxmlc",this,type);
                break;
            case "wzlist":
                initListContainer(usercontent_lc,"userwzlc",this,type);
                break;
            case "collectlist":
                initListContainer(usercontent_lc,"usercollectlc",this,type);
                break;
        }
        DownDataUserContentListInfo(type);
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
